var app = getApp();
Page({
  data: {
    currentType: 'coupon', // 当前选中类型：coupon-优惠券，exam-体检码
    hospitalId: "",

    // 优惠券历史记录
    couponHistory: [],
    couponPageNum: 1,
    couponPageSize: 10,
    couponHasMore: true,
    couponLoading: false,
    couponIsFirstLoad: true,
	iconSize: 40,
    // 体检码历史记录
    examHistory: [],
    examPageNum: 1,
    examPageSize: 10,
    examHasMore: true,
    examLoading: false,
    examIsFirstLoad: true,

    refreshing: false
  },

  onLoad(options) {
	
	const { windowWidth } = wx.getSystemInfoSync();
	this.setData({
	  hospitalId: options.hospital_id,
	  iconSize: Math.floor(windowWidth * 0.12) // 图标大小 = 屏幕宽度 * 12%
	});
	this.getHistoryList('coupon', true);
  },

  onShow() {
    const hasNewRecord = wx.getStorageSync('hasNewVerificationRecord') || false;
    if (hasNewRecord) {
      // 刷新当前类型的记录
      this.resetAndReloadCurrentType();
      wx.removeStorageSync('hasNewVerificationRecord');
    }
  },

  // 切换核销类型（标签点击）
  switchType(e) {
    const type = e.currentTarget.dataset.type;
    if (this.data.currentType === type) return;
    
    this.setData({ currentType: type });
    // 若切换后的类型无数据，加载第一页
    const historyData = this.data[type === 'coupon' ? 'couponHistory' : 'examHistory'];
    if (historyData.length === 0) {
      this.getHistoryList(type, true);
    }
  },

  // 滑动切换面板时同步更新标签
  onSwiperChange(e) {
    const current = e.detail.current;
    const type = current === 0 ? 'coupon' : 'exam';
    if (this.data.currentType !== type) {
      this.setData({ currentType: type });
      // 加载对应类型数据
      const historyData = this.data[type === 'coupon' ? 'couponHistory' : 'examHistory'];
      if (historyData.length === 0) {
        this.getHistoryList(type, true);
      }
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data[this.data.currentType + 'Loading']) return;
    this.resetAndReloadCurrentType().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    const type = this.data.currentType;
    const hasMore = this.data[type + 'HasMore'];
    const isLoading = this.data[type + 'Loading'];
    if (hasMore && !isLoading) {
      this.setData({ [type + 'PageNum']: this.data[type + 'PageNum'] + 1 });
      this.getHistoryList(type, false);
    }
  },

  // 重置并重新加载当前类型的记录
  resetAndReloadCurrentType() {
    const type = this.data.currentType;
    this.setData({
      [type + 'PageNum']: 1,
      [type + 'History']: [],
      [type + 'HasMore']: true
    });
    return this.getHistoryList(type, true);
  },

  // 获取指定类型的历史记录
  getHistoryList(type, isFirstPage) {
    const pageNum = this.data[type + 'PageNum'];
    const pageSize = this.data[type + 'PageSize'];
    const hospitalId = this.data.hospitalId;
    
    this.setData({ [type + 'Loading']: true });

    if (isFirstPage) {
      wx.showLoading({ 
        title: type === 'coupon' ? '加载优惠券记录...' : '加载体检码记录...', 
        mask: true 
      });
    }

    return new Promise((resolve) => {
      app.util.request({
        url: type === 'coupon' ? 'Coupon/hexiaohistory' : 'Physical/hexiaohistory',
        method: 'GET',
        data: { hospitalId, pageNum, pageSize, type: type === 'coupon' ? 1 : 2 },
        success: (res) => {
          if (res.data.code === 1 && res.data.data) {
            const newList = res.data.data.lists || [];
            const total = res.data.data.total || 0;
            const hasMore = pageNum * pageSize < total;
            
            this.setData({
              [type + 'History']: isFirstPage ? newList : [...this.data[type + 'History'], ...newList],
              [type + 'HasMore']: hasMore,
              [type + 'IsFirstLoad']: false
            });
          } else {
            wx.showToast({
              title: res.data.msg || (type === 'coupon' ? '获取优惠券记录失败' : '获取体检码记录失败'),
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
        },
        complete: () => {
          this.setData({ [type + 'Loading']: false });
          wx.hideLoading();
          resolve();
        }
      });
    });
  },

  // 优惠券核销扫码
  handleVerification() {
    wx.scanCode({
      onlyFromCamera: true,
      scanType: ['qrCode', 'barCode'],
      success: (res) => {
        const result = res.result;
        if (this.isValidCode(result)) {
          this.verifyCode(result, 'coupon');
        } else {
          wx.showToast({ title: '无效的优惠券码', icon: 'none' });
        }
      },
      fail: (err) => this.handleScanError(err)
    });
  },

  // 体检码核销扫码
  handlePhysicalExamVerification() {
    wx.scanCode({
      onlyFromCamera: true,
      scanType: ['qrCode', 'barCode'],
      success: (res) => {
        const result = res.result;
        if (this.isValidCode(result)) {
          this.verifyCode(result, 'exam');
        } else {
          wx.showToast({ title: '无效的体检码', icon: 'none' });
        }
      },
      fail: (err) => this.handleScanError(err)
    });
  },

  // 通用验证扫码结果
  verifyCode(code, type) {
    const hospitalId = this.data.hospitalId;
    const url = type === 'coupon' ? 'Coupon/checkcoupon' : 'Physical/checkPhysicalCode';
    
    app.util.request({
      url,
      method: 'GET',
      data: { hospitalId, code },
      success: (res) => {
        if (res.data.data.code === 200) {
          wx.navigateTo({
            url: `/vp_pz/pages/admin/verifyAmount?code=${encodeURIComponent(code)}&hospitalId=${hospitalId}&type=${type === 'coupon' ? 1 : 2}`
          });
        } else {
          wx.showToast({ title: res.data.data.msg || '验证失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
      }
    });
  },

  // 扫码错误处理
  handleScanError(err) {
    if (err.errMsg !== 'scanCode:fail cancel') {
      wx.showToast({ title: '扫码失败，请重试', icon: 'none' });
    }
  },

  // 验证代码有效性
  isValidCode(code) {
    return code && code.trim() !== '';
  }
});